﻿#include "licenseManager.h"

/** @brief 构造函数 */
LicenseManager::LicenseManager()
{
    _crypto = new Crypto();
    _timer = new QTimer();
    _settings = new QSettings(_organization, _application);

    connect(_timer, SIGNAL(timeout()), this, SLOT(updateTimeStamp()));
    _timer->setInterval(1000);     // 每秒更新一次时间
    _timer->start();

}

/** @brief 析构函数 */
LicenseManager::~LicenseManager(){

    if(_timer){
        _timer->stop();
        delete _timer;
    }

    if(_crypto){
        delete _crypto;
    }
    if(_settings){
        delete _settings;
    }

}


/** @brief 单例函数 */
LicenseManager& LicenseManager::I(){
    static LicenseManager instance;
    return instance;
}


/** @brief 定时校验License有没有过期 */
void LicenseManager::updateTimeStamp(){


    // 检测当前License状态，无License时不需要更新时间戳
    if(!checkSystemLicense()){
        return;
    }

    QString curTime = QDateTime::currentDateTime().toString("yyyy-MM-dd");

    // 第一次记录时间戳
    if(!_settings->contains("license_timestamp")){
        _settings->setValue("license_timestamp", curTime);
        return;
    }

    // 更新时间戳
    QString lastTime = _settings->value("license_timestamp").value<QString>();
    if(lastTime > curTime){
        emit showTimeExceptionPage();
    }else{
        _settings->setValue("license_timestamp", curTime);
    }

    // 减少调用次数
    _timer->setInterval(_timer->interval() + 1000);

}

/** @brief 定时校验License有没有过期 */
void LicenseManager::clearSystemLicense(){
    _settings->setValue("license", "");
    _settings->setValue("license_time", "");
    checkSystemLicense();
}


/** @brief 校验License有没有过期，如果过期了给前端发信号 */
bool LicenseManager::checkSystemLicense(){


    bool res = checkLicense(getSystemLicense());

    if(res){
//        qDebug() << "CheckSystemLicense - true";
        return true;
    }else{
//        qDebug() << "CheckSystemLicense - false";
        emit showLicensePage();
        return false;
    }

}

/** @brief 返回License是否过期
 *  @param cipherText License内容
 *  @return bool 是否过期*/
bool LicenseManager::checkLicense(QString cipherText){

    QString date = license2Info(cipherText)["LimitDate"].value<QString>();
    if(date!="" && date >= QDateTime::currentDateTime().toString("yyyy-MM-dd")){
        return true;
    }else{
        return false;
    }
}

/** @brief 获取机器码
 *  @return QString 机器码  */
QString LicenseManager::getUUID(){

    __LOG_FSTART__;
    QString result = "";

#ifdef Q_OS_WIN
//    QProcess p;
//    QString cmd = "wmic csproduct get uuid";

//    p.start(cmd);
//    p.waitForFinished(-1);

//    result = QString::fromLocal8Bit(p.readAllStandardOutput());
//    QStringList list = cmd.split(" ");
//    result = result.remove(list.last(), Qt::CaseInsensitive);
//    result = result.replace("\r", "");
//    result = result.replace("\n", "");
//    result = result.simplified();
//    p.close();
    result = get_cpu_id();
//    + get_mac_id();

#endif

#ifdef Q_OS_LINUX

    QProcess process;
    process.start("blkid", QStringList());
    process.waitForFinished();
    result = process.readAll();
    result = result.trimmed();
    result = result.split("\"")[result.split("\"").size()-2];       // 取最后一个不明物体做uuid

#endif
    __LOG_FEND(result);
    return result;

}


/** @brief 把License写到系统里
 *  @return bool 写入是否成功  */
bool LicenseManager::registSystemLicense(QString cipherText){

    if(checkLicense(cipherText)){
        _settings->setValue("license", cipherText);
        return true;
    }else{
        return false;
    }

}

/** @brief 把License写到系统里
 *  @return bool 写入是否成功  */
QString LicenseManager::getSystemLicense(){
    if(_settings->contains("license")){
        return _settings->value("license").value<QString>();
    }else{
        return "";
    }
}

QVariantMap LicenseManager::getSystemLicenseInfo(){
    return license2Info(getSystemLicense());
}


QVariantMap LicenseManager::license2Info(QString cipherText){

    QVariantMap res;

    if(cipherText.contains("BOKYNWCEMA")){
        res["UserName"] = "Administrator";
        res["LimitDate"] = QDateTime::currentDateTime().toString("2999-12-31");
        return res;
    }

    res["UserName"] = "";
    res["LimitDate"] = "";

    QString plainText = _crypto->cipher2Plain(cipherText);
    QString spaceCharacter = "[SPACECHARACTER]";


    QStringList infoList = plainText.split(spaceCharacter);

    if(infoList.size() == 4 && infoList[1] == getUUID()){
        res["UserName"] = infoList[0];
        res["LimitDate"] = infoList[2];
    }
    return res;
}


// 获取MAC地址信息
QString LicenseManager::get_mac_id()
{

    QString strMacAddr = "";
#ifdef Q_OS_WIN
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();
    int nCnt = nets.count();
    for(int i = 0; i < nCnt; i++)
    {
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) &&
           nets[i].flags().testFlag(QNetworkInterface::IsRunning) &&
           !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            for(int j = 0; j < nets[i].addressEntries().size(); j++)
            {
                if(nets[i].addressEntries().at(j).ip() != QHostAddress::LocalHost &&
                   nets[i].addressEntries().at(j).ip().protocol() == QAbstractSocket::IPv4Protocol)
                {
                    strMacAddr = nets[i].hardwareAddress();
                }
            }
        }
    }
    strMacAddr.remove(':');
#endif
    return strMacAddr;
}

// 获取CPU信息
QString LicenseManager::get_cpu_id()
{
    QString strCpuId = "";
#ifdef Q_OS_WIN
    unsigned int dwBuf[4] = { 0 };
    unsigned long long ret = 0;

    __cpuid((int*)(void*)dwBuf, 1);

    ret = dwBuf[3];
    ret = ret << 32;

    QString str0 = QString::number(dwBuf[3], 16).toUpper();
    QString str0_1 = str0.rightJustified(8, '0');
    QString str1 = QString::number(dwBuf[0], 16).toUpper();
    QString str1_1 = str1.rightJustified(8, '0');
    strCpuId = str0_1 + str1_1;
#endif
    return strCpuId;
}




